package tgc.edu.yzy.web.admin.controller;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import tgc.edu.yzy.custom.Custom;
import tgc.edu.yzy.custom.DatagridUtils;
import tgc.edu.yzy.entity.BmsRole;
import tgc.edu.yzy.entity.Book;
import tgc.edu.yzy.entity.BookRecord;
import tgc.edu.yzy.entity.User;
import tgc.edu.yzy.service.BookRecordService;
import tgc.edu.yzy.service.BookService;
import tgc.edu.yzy.service.RecordService;
import tgc.edu.yzy.service.RegisterService;
import tgc.edu.yzy.service.UserService;
import tgc.edu.yzy.web.admin.form.BookForm;

@Controller
@RequestMapping("/admin/book")
public class BookController {
	
	@Autowired//书本
	private BookService bookservice;
	@Autowired
	private Custom custom;
	@Autowired
	private UserService userservice;
	@Autowired
	private RegisterService registerservice;
	@Autowired
	private BookRecordService bookrecord;
	/***
	 * 跳转到图书的管理界面
	 * 图书管理员
	 * @return
	 */
	@RequestMapping(value="bom")
	private String books() {
		return "admin/book/bom";
	}
	/***
	 * 遍历图书
	 * 图书管理员
	 * @param form
	 * @param book
	 * @return
	 */
	@RequestMapping(value="pagelist")
	@ResponseBody
	private Object pagelist(DatagridUtils form,Book book) {
		Pageable pageable=form.buildPageable();
		Page<Book> books=null;
		Specification<Book> spec = new Specification<Book>() {

			@Override
			public Predicate toPredicate(Root<Book> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				HashSet<Predicate> rules = new HashSet<>();
				if(StringUtils.hasText(book.getName())) {
					rules.add(criteriaBuilder.like(root.get("name"), "%"+book.getName()+"%"));
				}else if(StringUtils.hasText(book.getIsbn())) {
					rules.add(criteriaBuilder.like(root.get("isbn"), "%"+book.getIsbn()+"%"));
				}else if(StringUtils.hasText(book.getAuthor())) {
					rules.add(criteriaBuilder.like(root.get("author"), "%"+book.getAuthor()+"%"));
				}else if(StringUtils.hasText(book.getPress())) {
					rules.add(criteriaBuilder.like(root.get("press"), "%"+book.getPress()+"%"));
				}
				return criteriaBuilder.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		books= bookservice.findAll(spec,pageable);
		HashMap<String , Object> result = form.getPageResult(books);
		return result; 
	}
	/***
	 * 新增图书
	 * 图书管理员进行操作
	 * @param form
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value="save")
	@ResponseBody
	private Object save(BookForm form,MultipartFile file) {
		String f = file.getContentType();
		if(f.equals("image/gif")||f.equals("image/jpeg")||f.equals("image/jpg")||f.equals("image/png")||f.equals("image/svg")||f.equals("application/octet-stream")) {
			String o=file.getOriginalFilename();
			if(!"".equals(o)&&f.equals("application/octet-stream")) {
				return "no";
			}
			Book book=null;
			if(form.getId()!=null) {
				 book = bookservice.findById(form.getId());
				 //获取number的值
				 Integer numbers=book.getNumber();
				 if(!form.getIsbn().equals(book.getIsbn())) {
					 Book isbn=bookservice.findByIsbn(form.getIsbn());
					 if(isbn!=null) {
						 return "isbn";
					 }
				 }
				 BeanUtils.copyProperties(form, book);
				 String or = file.getOriginalFilename();
				 
				 if(!"".equals(or)) {
					book.setFilename(file.getOriginalFilename());
					book.setUuid(custom.file(file));
				 }
				 if(numbers-form.getNumber()!=0) {
					 Integer loan = book.getLoan();
					 loan=loan+(form.getNumber()-numbers);
					 
					 book.setLoan(loan);
					 book.setState(book.getState()+(form.getNumber()-numbers));
					 if(loan<1) {
						 book.setLoan(0);
					 }
					 if((book.getState()+(form.getNumber()-numbers))<1) {
						 book.setState(0);
					 }
				 }
				 bookservice.save(book);
			}else {/* 当id为空 为新增 */
				Book isbn=bookservice.findByIsbn(form.getIsbn());
				 if(isbn!=null) {
					 return "isbn";
				 }
				book=new Book();
				BeanUtils.copyProperties(form, book);
				book.setLoan(form.getNumber());
				book.setState(form.getNumber());
				book.setFilename(file.getOriginalFilename());
				book.setUuid(custom.file(file));
				bookservice.save(book);
			}
			return "ok";
		}else {
			return "no";
		}
		
	}
	/***
	 * 下载图片  （显示图片） 
	 * 鼠标停放显示图片
	 * 图书管理员
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/download")
	@ResponseBody
	public Object download(Integer id,HttpServletRequest request,HttpServletResponse response) {
		custom.download(id,request,response);
		return null;
	}
	/***
	 * 删除图片
	 * 图书管理员操作
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/delete")
	@ResponseBody
	public Object delete(Integer id) {
		bookservice.deleteByID(id);
		return null;
	}
	/***
	 * 借书
	 * 需要改变三张表（必须加同步）
	 * 1.首先修改 借书记录
	 * 2.修改用户里新增一本图书
	 * 3.书籍状态减少一本书
	 * 4.加一条记录
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/borrow")
	@ResponseBody
	public String borrow(Integer id) {
		//首先处理图书
		Book books = bookservice.findById(id);
		User users = userservice.findById(custom.userid());
		Integer state = books.getState();
		if(state>0) {
			List<BmsRole> bmsRole = users.getBmsRole();
			String code=null;
			for (BmsRole role : bmsRole) {
				code=role.getCode();
			}
			if("ROLE_USER".equals(code)) {//用户借书
				state=state-1;
				books.setState(state);
				bookservice.save(books);
				
				//新增一条借书记录
				BookRecord br=new BookRecord();
				br.setBook(books);
				br.setUser(users); 
				br.setName(users.getName());
				br.setState("等待处理");
				br.setStartTime(custom.time());
				bookrecord.save(br);
				//最后加记录
				custom.booksrecord(users,books, "申请借书", "用户正在申请借书");
				return "ok";
			}else {//管理员借书
				state=state-1;
				books.setState(state);
				Integer loan=books.getLoan()-1;
				books.setLoan(loan);
				bookservice.save(books);
				
				//处理个人数据
				Integer number=users.getNumber()+1;
				users.setNumber(number);
				userservice.save(users);
				
				//新增一条借书记录
				BookRecord br=new BookRecord();
				br.setBook(books);
				br.setUser(users); 
				br.setName(users.getName());
				br.setState("同意借书");
				br.setStartTime(custom.time());
				bookrecord.save(br);
				
				custom.booksrecord(users,books, "同意借书", "图书管理员借阅了一本图书");
				return "oks";
			}
		}else {
			return "图书已被借出";
		}
	}
}
